from django.db import models
from django.utils import timezone
from django.core.validators import MinValueValidator, MaxValueValidator
import uuid


class SafetyEvaluation(models.Model):
    """
    矿山安全评价模型
    包含矿山基本信息和15个安全指标的评价数据
    """
    
    # ====== 矿山基本信息 ======
    evaluation_id = models.CharField(
        max_length=50, 
        unique=True,
        blank=True,  # 允许表单中为空
        verbose_name="评价编号",
        help_text="系统自动生成唯一编号（如 SAFE20251002-001）"
    )
    
    evaluation_date = models.DateField(
        default=timezone.now,
        verbose_name="评价日期",
        help_text="当前评价日期"
    )
    
    evaluator_name = models.CharField(
        max_length=100,
        verbose_name="评价人",
        help_text="当前执行评价的人员姓名"
    )
    
    mine_name = models.CharField(
        max_length=200,
        verbose_name="矿山名称",
        help_text="被评价矿山名称"
    )
    
    # 所属区域选择
    REGION_CHOICES = [
        ('beijing', '北京市'),
        ('tianjin', '天津市'),
        ('hebei', '河北省'),
        ('shanxi', '山西省'),
        ('inner_mongolia', '内蒙古自治区'),
        ('liaoning', '辽宁省'),
        ('jilin', '吉林省'),
        ('heilongjiang', '黑龙江省'),
        ('shanghai', '上海市'),
        ('jiangsu', '江苏省'),
        ('zhejiang', '浙江省'),
        ('anhui', '安徽省'),
        ('fujian', '福建省'),
        ('jiangxi', '江西省'),
        ('shandong', '山东省'),
        ('henan', '河南省'),
        ('hubei', '湖北省'),
        ('hunan', '湖南省'),
        ('guangdong', '广东省'),
        ('guangxi', '广西壮族自治区'),
        ('hainan', '海南省'),
        ('chongqing', '重庆市'),
        ('sichuan', '四川省'),
        ('guizhou', '贵州省'),
        ('yunnan', '云南省'),
        ('tibet', '西藏自治区'),
        ('shaanxi', '陕西省'),
        ('gansu', '甘肃省'),
        ('qinghai', '青海省'),
        ('ningxia', '宁夏回族自治区'),
        ('xinjiang', '新疆维吾尔自治区'),
    ]
    
    region = models.CharField(
        max_length=50,
        choices=REGION_CHOICES,
        verbose_name="所属区域",
        help_text="所在省、市或矿区"
    )
    
    # 评价对象类别
    EVALUATION_CATEGORY_CHOICES = [
        ('coal_mine', '煤矿'),
        ('metal_mine', '金属矿'),
        ('non_metal_mine', '非金属矿'),
    ]
    
    evaluation_category = models.CharField(
        max_length=20,
        choices=EVALUATION_CATEGORY_CHOICES,
        verbose_name="评价对象类别",
        help_text="可选煤矿、金属矿、非金属矿等"
    )
    
    # ====== 新增矿山基本信息字段 ======
    affiliated_enterprise = models.CharField(
        max_length=200,
        blank=True,
        verbose_name="隶属企业名字",
        help_text="矿山所属的企业名称"
    )
    
    production_capacity = models.FloatField(
        default=100.0,
        validators=[MinValueValidator(0.1)],
        verbose_name="生产能力（万吨/年）",
        help_text="矿山年生产能力，单位：万吨/年"
    )
    
    service_life = models.IntegerField(
        default=30,
        validators=[MinValueValidator(1)],
        verbose_name="服务年限（年）",
        help_text="矿山预计服务年限，单位：年"
    )
    
    # 开拓方式选择（多选）
    DEVELOPMENT_METHOD_CHOICES = [
        ('inclined_shaft', '斜井'),
        ('vertical_shaft', '立井'),
        ('adit', '平硐'),
    ]
    
    development_methods = models.JSONField(
        default=list,
        verbose_name="开拓方式",
        help_text="矿山开拓方式，可多选"
    )
    
    # 运输方式选择（单选）
    TRANSPORT_METHOD_CHOICES = [
        ('electric_locomotive', '电机车运输'),
        ('belt_conveyor', '带式运送机运输'),
    ]
    
    transport_method = models.CharField(
        max_length=30,
        choices=TRANSPORT_METHOD_CHOICES,
        blank=True,
        verbose_name="运输方式",
        help_text="矿山主要运输方式"
    )
    
    # ====== 生产系统信息 ======
    current_production_system = models.CharField(
        max_length=50,
        default='mining_system',
        verbose_name="当前生产系统",
        help_text="当前选中的生产系统"
    )
    
    production_systems = models.JSONField(
        default=dict,
        verbose_name="生产系统信息",
        help_text="各生产系统的详细信息"
    )
    
    # ====== 15个安全指标（0-100浮点数，包含开发阶段默认值） ======
    
    worker_safety_awareness = models.FloatField(
        default=75.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="工人安全意识与操作能力",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 75.0"
    )
    
    management_capability = models.FloatField(
        default=80.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="管理人员的管理能力",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 80.0"
    )
    
    mining_equipment_integrity = models.FloatField(
        default=85.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="采掘设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 85.0"
    )
    
    ventilation_equipment_integrity = models.FloatField(
        default=90.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="矿井通风设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 90.0"
    )
    
    gas_monitoring_equipment_integrity = models.FloatField(
        default=88.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="瓦斯监测设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 88.0"
    )
    
    fire_prevention_equipment_integrity = models.FloatField(
        default=82.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="防火及消防设施完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 82.0"
    )
    
    drainage_equipment_integrity = models.FloatField(
        default=87.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="井下排水设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 87.0"
    )
    
    hoisting_equipment_integrity = models.FloatField(
        default=91.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="矿井提升设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 91.0"
    )
    
    power_system_integrity = models.FloatField(
        default=89.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="供电系统设备完好率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 89.0"
    )
    
    air_supply_demand_ratio = models.FloatField(
        default=78.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="风量供需比",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 78.0"
    )
    
    roof_management_difficulty = models.FloatField(
        default=70.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="顶板管理难易程度",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 70.0（数值越高表示管理越容易）"
    )
    
    coal_spontaneous_combustion_tendency = models.FloatField(
        default=65.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="煤层自燃发火倾向性",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 65.0（数值越高表示自燃倾向性越低）"
    )
    
    safety_management_implementation = models.FloatField(
        default=83.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="安全管理制度及落实率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 83.0"
    )
    
    emergency_response_completeness = models.FloatField(
        default=77.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="应急响应机制完善率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 77.0"
    )
    
    safety_inspection_implementation = models.FloatField(
        default=81.0,
        validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
        verbose_name="安全检查整改落实率",
        help_text="评价范围: 0.0-100.0，开发阶段默认值: 81.0"
    )
    
    # ====== 安全等级字段 ======
    comprehensive_score = models.FloatField(
        blank=True,
        null=True,
        verbose_name="综合得分",
        help_text="基于AHP-MIV-BP模型计算的综合安全得分（0.0-1.0）"
    )
    
    safety_level = models.CharField(
        max_length=20,
        blank=True,
        null=True,
        verbose_name="安全等级",
        help_text="基于AHP-MIV-BP模型计算的安全等级（A级/B级/C级/D级）"
    )
    
    # ====== 元数据字段 ======
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )
    
    class Meta:
        verbose_name = "安全评价"
        verbose_name_plural = "安全评价记录"
        ordering = ['-created_at']  # 按创建时间倒序排列
        
    def save(self, *args, **kwargs):
        """
        重写保存方法，自动生成评价编号和安全等级
        """
        if not self.evaluation_id:
            # 生成格式: SAFE + 年月日 + 3位序号
            today = timezone.now().strftime('%Y%m%d')
            # 获取今天已有的评价数量
            count = SafetyEvaluation.objects.filter(
                evaluation_id__startswith=f'SAFE{today}'
            ).count()
            self.evaluation_id = f'SAFE{today}-{count + 1:03d}'
        
        # 自动计算并存储安全等级
        if not self.safety_level:
            self.safety_level = self.get_safety_level()
        
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f"{self.evaluation_id} - {self.mine_name}"
    
    def get_safety_indicators_dict(self):
        """
        返回15个安全指标的字典格式，便于前端使用
        """
        return {
            'worker_safety_awareness': self.worker_safety_awareness,
            'management_capability': self.management_capability,
            'mining_equipment_integrity': self.mining_equipment_integrity,
            'ventilation_equipment_integrity': self.ventilation_equipment_integrity,
            'gas_monitoring_equipment_integrity': self.gas_monitoring_equipment_integrity,
            'fire_prevention_equipment_integrity': self.fire_prevention_equipment_integrity,
            'drainage_equipment_integrity': self.drainage_equipment_integrity,
            'hoisting_equipment_integrity': self.hoisting_equipment_integrity,
            'power_system_integrity': self.power_system_integrity,
            'air_supply_demand_ratio': self.air_supply_demand_ratio,
            'roof_management_difficulty': self.roof_management_difficulty,
            'coal_spontaneous_combustion_tendency': self.coal_spontaneous_combustion_tendency,
            'safety_management_implementation': self.safety_management_implementation,
            'emergency_response_completeness': self.emergency_response_completeness,
            'safety_inspection_implementation': self.safety_inspection_implementation,
        }
    
    def get_mine_basic_info_dict(self):
        """
        返回矿山基本信息的字典格式，包括新增字段
        """
        return {
            'affiliated_enterprise': self.affiliated_enterprise,
            'production_capacity': self.production_capacity,
            'service_life': self.service_life,
            'development_methods': self.development_methods,
            'transport_method': self.transport_method,
            'current_production_system': self.current_production_system,
            'production_systems': self.production_systems,
        }
    
    def get_development_methods_display(self):
        """
        获取开拓方式的显示文本
        """
        if not self.development_methods:
            return "未选择"
        
        method_names = []
        for method in self.development_methods:
            for choice_value, choice_label in self.DEVELOPMENT_METHOD_CHOICES:
                if method == choice_value:
                    method_names.append(choice_label)
                    break
        
        return "、".join(method_names) if method_names else "未选择"
    
    def get_transport_method_display(self):
        """
        获取运输方式的显示文本
        """
        if not self.transport_method:
            return "未选择"
        
        for choice_value, choice_label in self.TRANSPORT_METHOD_CHOICES:
            if self.transport_method == choice_value:
                return choice_label
        
        return "未选择"
    
    def get_production_system_names(self):
        """
        获取所有生产系统的名称列表
        """
        if not self.production_systems:
            return []
        
        return [system.get('system_name', '未知系统') for system in self.production_systems.values()]
    
    def get_current_system_info(self):
        """
        获取当前选中生产系统的详细信息
        """
        if not self.production_systems or not self.current_production_system:
            return None
        
        return self.production_systems.get(self.current_production_system, None)
    
    def get_system_operation_status_display(self, system_key):
        """
        获取指定系统运行状态的显示文本
        """
        if not self.production_systems or system_key not in self.production_systems:
            return "未知"
        
        status = self.production_systems[system_key].get('operation_status', 'normal')
        status_mapping = {
            'normal': '正常',
            'attention': '注意',
            'abnormal': '异常'
        }
        
        return status_mapping.get(status, '未知')
    
    def get_all_systems_summary(self):
        """
        获取所有生产系统的摘要信息
        """
        if not self.production_systems:
            return []
        
        summary = []
        for system_key, system_info in self.production_systems.items():
            summary.append({
                'system_key': system_key,
                'system_name': system_info.get('system_name', '未知系统'),
                'operation_status': system_info.get('operation_status', 'normal'),
                'operation_status_display': self.get_system_operation_status_display(system_key),
                'safety_hazards': system_info.get('safety_hazards', ''),
                'main_facilities': system_info.get('main_facilities', '')
            })
        
        return summary
    
    def calculate_comprehensive_score(self):
        """
        计算综合安全评价得分
        这里提供一个基础的加权平均计算方法，可根据实际需要调整权重
        注意：指标值现在是0-100范围，需要先归一化为0-1再计算
        """
        indicators = self.get_safety_indicators_dict()
        
        # 设定各指标权重（可根据实际情况调整）
        weights = {
            'worker_safety_awareness': 0.08,
            'management_capability': 0.10,
            'mining_equipment_integrity': 0.07,
            'ventilation_equipment_integrity': 0.08,
            'gas_monitoring_equipment_integrity': 0.08,
            'fire_prevention_equipment_integrity': 0.06,
            'drainage_equipment_integrity': 0.06,
            'hoisting_equipment_integrity': 0.07,
            'power_system_integrity': 0.07,
            'air_supply_demand_ratio': 0.06,
            'roof_management_difficulty': 0.05,
            'coal_spontaneous_combustion_tendency': 0.05,
            'safety_management_implementation': 0.09,
            'emergency_response_completeness': 0.08,
            'safety_inspection_implementation': 0.10,
        }
        
        # 计算加权得分（先将0-100的值归一化为0-1）
        weighted_score = sum(
            (indicators[key] / 100.0) * weights[key] 
            for key in indicators.keys()
        )
        
        return round(weighted_score, 4)
    
    def get_safety_level(self):
        """
        获取安全等级，优先返回存储的等级，否则根据综合得分计算
        """
        # 如果已存储安全等级，直接返回
        if self.safety_level:
            return self.safety_level
        
        # 否则根据综合得分计算
        score = self.comprehensive_score if self.comprehensive_score is not None else self.calculate_comprehensive_score()
        
        if score >= 0.90:
            return "A级(优秀)"
        elif score >= 0.80:
            return "B级(良好)"
        elif score >= 0.70:
            return "C级(一般)"
        else:
            return "D级(较差)"
    
    def save_calculation_results(self):
        """
        计算并保存安全等级和综合得分到数据库
        """
        # 计算综合得分
        score = self.calculate_comprehensive_score()
        
        # 根据得分确定安全等级
        if score >= 0.90:
            level = "A级(优秀)"
        elif score >= 0.80:
            level = "B级(良好)"
        elif score >= 0.70:
            level = "C级(一般)"
        else:
            level = "D级(较差)"
        
        # 更新字段
        self.comprehensive_score = score
        self.safety_level = level
        
        # 保存到数据库
        self.save(update_fields=['comprehensive_score', 'safety_level'])
        
        return {
            'comprehensive_score': score,
            'safety_level': level
        }
    
    def _get_safety_level_description(self, level):
        """获取安全等级说明"""
        descriptions = {
            "A级(优秀)": '安全等级优秀，各项安全指标表现良好，安全管理到位。',
            "B级(良好)": '安全等级良好，整体安全状况较好，存在少量需要改进的地方。',
            "C级(一般)": '安全等级一般，存在一定安全隐患，需要重点关注和改进。',
            "D级(较差)": '安全等级较差，存在一定安全隐患，需要加强管理和整改。'
        }
        return descriptions.get(level, '等级说明暂无')